import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Tabs, Space, Button, Form, Row, Col, Input, message, Checkbox, notification, Modal, Table, InputNumber } from 'antd';
import { connect } from 'umi';
import {
    PlusOutlined,
    CloseOutlined,
    SyncOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import DMRActn from './components/dmrActn'
import request from '@/utils/request';
import moment from 'moment';
import IconFont from '@/components/Iconfont';

const { TabPane } = Tabs;
const { Search } = Input;
const { confirm } = Modal;
const apiURL = "/api/services/app/DMRHead/";
const currentControl = "DMRHead";
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
            dataSource: [],
            data: {
                data: { dmrNum: '0', id: '0' },
                details: []
            },
            defTab: '1',
            pageIndex: 1,
            pageSize: 10,
            selectedRowKeys: []
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.formRef.current.setFieldsValue({ DMRHead: this.state.data });
        this.fetchDatas()
    }
    fetchDatas = () => {
        const { pageIndex, pageSize, keywords } = this.state;
        this.setState({ loading2: true })
        this.props.dispatch({
            type: 'Abp/getList',
            payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords },
            control: currentControl
        }).then(() => {
            var result = this.props.response.result;
            if (result) {
                this.setState({ dataSource: result.items, totalCount: result.totalCount, loading2: false });
            }
        })
    }
    onFinish = (values: any) => {
        const { defTab } = this.state
        if (defTab === '1') {
            this.save(values.DMRHead);
        }
        else {
            this.inspDtl.formRef.current.submit();
        }

    }
    resetForm = () => {
        let data = {
            data: { dmrNum: '0', id: '0' },
            details: []
        }
        this.formRef.current.resetFields()
        this.formRef.current.setFieldsValue({ DMRHead: data.data });
        this.setState({ data })
    }
    save = (model: any) => {
        var act = 'Modify'
        var method = 'POST'
        if (model.id === "0") {
            act = 'New'
        }
        request(apiURL + act, {
            method,
            data: model,
        }).then((response) => {
            if (response) {
                if (response.success) {
                    message.success('保存成功！');
                    this.getObj(model.inspNum)
                }
                else {
                    notification.error({
                        message: response.error.message,
                        description: response.error.details,
                    });
                }
                this.setState({ loading: false });
            }
        });
    }
    tabSwitch = (key: any) => {
        this.setState({ defTab: key });
    }
    getObj = (value: any) => {
        if (!value) {
            return;
        }
        this.setState({ loading: true })
        request(apiURL + 'GetByNum', {
            method: 'GET',
            params: { num: value },
        }).then((response) => {
            if (response) {
                if (response.success) {
                    var result = response.result;
                    var DMRHead = response.result.data;
                    if (DMRHead) {
                        if (DMRHead.inspDate)
                            DMRHead.inspDate = moment(DMRHead.inspDate);
                        this.formRef.current.setFieldsValue({ DMRHead });
                        this.setState({ data: result, visible: false, loading: false })
                    }
                }
                else {
                    notification.error({
                        message: response.error.message,
                        description: response.error.details,
                    });
                }
                this.setState({ loading: false });
            }
        });
    }
    delObj = () => {
        const { data } = this.state;
        if (data.data) {
            let _this = this
            confirm({
                title: '警告',
                icon: <ExclamationCircleOutlined />,
                content: '删除后将不可恢复，确定删除？',
                onOk() {
                    _this.props.dispatch({
                        type: 'Abp/delete',
                        payload: { id: data.data.id },
                        control: currentControl
                    }).then(() => {
                        _this.fetchDatas()
                        _this.resetForm()
                    })
                },
            });
        }
    }
    switchModal = (visible: boolean, record: any = null) => {
        const { data } = this.state;
        if (record == null) {
            record = {
                dmrNum: data.data.dmrNum,
                partNum: data.data.partNum,
                partDescription: data.data.partDescription,
                quantity: data.data.quantity,
                ium: data.data.ium,
            }
        }
        else {
            record.partNum = data.data.partNum
            record.partDescription = data.data.partDescription
            record.ium = data.data.ium
        }
        this.setState({ visible, record });
    }
    inspDtl: any = DMRActn;
    onRef = (ref: any) => {
        this.inspDtl = ref
    }
    onSearch = (value: any) => {
        var keywords = this.state.keywords;
        keywords = value;
        this.setState({ keywords }, () => {
            this.fetchDatas();
        });
    }
    delDtl = () => {
        const { selectedRowKeys, data } = this.state
        let _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.props.dispatch({
                    type: 'Abp/delPatch',
                    payload: selectedRowKeys,
                    control: 'DMRActn'
                }).then(() => {
                    let _data = data
                    _data.details = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0)
                    _this.setState({ data: _data })
                })
            },
        });
    }
    render() {
        const layout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
        };
        const { data, defTab, record, dataSource, pageSize, totalCount, loading, loading2, selectedRowKeys } = this.state
        const columns = [
            {
                title: 'DMR号',
                dataIndex: 'dmrNum',
            },
            {
                title: '处理日期',
                dataIndex: 'actionDate',
                render: (text: string) => (
                    <span>{moment(text).format('YYYY-MM-DD')}</span>
                )
            },
            {
                title: '仓库',
                dataIndex: 'warehouseCode',
            },
            {
                title: '库位',
                dataIndex: 'binNum',
            },
            {
                title: '数量',
                dataIndex: 'quantity',
            },
            {
                title: '单位',
                dataIndex: 'ium',
            },
            {
                title: '未结',
                dataIndex: 'openDMR',
                key: 'openDMR',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
        ]
        const columns2 = [
            {
                width: 30,
                render: () => <IconFont type="icon-database" />
            },
            {
                title: 'DMR号',
                dataIndex: 'dmrNum',
            },
            {
                title: '产生日期',
                dataIndex: 'creationTime',
                render: (text: string) => (
                    <span>{moment(text).format('YYYY-MM-DD')}</span>
                )
            },
            {
                title: '物料编码',
                dataIndex: 'partNum',
            },
            {
                title: '物料描述',
                dataIndex: 'partDescription',
            },
            {
                title: '未结',
                dataIndex: 'openDMR',
                key: 'openDMR',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
        ]
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys: any) => {
                this.setState({ selectedRowKeys });
            },
        };
        return (
            <PageHeaderWrapper title={false}>
                <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                    <Card title="DMR处理" extra={<Space>
                        <Button key="1" type="primary" icon={<PlusOutlined />} onClick={this.resetForm}>新建</Button>
                        <Button key="2" type="primary" htmlType="submit">保存</Button>
                        <Button key="4" type="dashed" danger icon={<CloseOutlined />} onClick={this.delObj} disabled={data.data.id === "0"}>删除</Button>
                    </Space>}>
                        <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
                            <TabPane tab="汇总" key="1">
                                <Row>
                                    <Col span={12}>
                                        <Form.Item name={['DMRHead', 'id']} hidden={true}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item name={['DMRHead', 'dmrNum']} label="DMR号"
                                            rules={[{ required: true, message: "DMR号必填" }]}>
                                            <Input style={{ width: 200 }} onBlur={(e: any) => this.getObj(e.target.value)} disabled />
                                        </Form.Item>
                                        <Form.Item label="物料编码" style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <Form.Item name={['DMRHead', 'partNum']}
                                                    rules={[{ required: true, message: "物料编码必填" }]}>
                                                    <Input disabled style={{ width: 130 }} />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'ium']}
                                                    rules={[{ required: true, message: "单位必填" }]}>
                                                    <Input disabled placeholder="单位" style={{ width: 70 }} />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'revisionNum']}>
                                                    <Input disabled placeholder="版本" style={{ width: 70 }} />
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                        <Form.Item name={['DMRHead', 'partDescription']} label="物料描述"
                                            rules={[{ required: true, message: "物料描述必填" }]}>
                                            <Input disabled />
                                        </Form.Item>
                                        <Form.Item label="工单" style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <Form.Item name={['DMRHead', 'jobNum']}>
                                                    <Input disabled style={{ width: 120 }} placeholder="工单号" />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'assemblySeq']}>
                                                    <Input disabled placeholder="半成品" style={{ width: 80 }} />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'mtlSeq']}>
                                                    <Input disabled placeholder="物料号" style={{ width: 80 }} />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'jobSeq']}>
                                                    <Input disabled placeholder="工序号" style={{ width: 80 }} />
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                        <Form.Item label="采购单" style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <Form.Item name={['DMRHead', 'poNum']}>
                                                    <Input disabled style={{ width: 120 }} placeholder="采购单号" />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'poLine']}>
                                                    <Input disabled style={{ width: 80 }} placeholder="分录" />
                                                </Form.Item>
                                                <Form.Item name={['DMRHead', 'poRelNum']}>
                                                    <Input disabled style={{ width: 80 }} placeholder="收货行" />
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item name={['DMRHead', 'commentText']} label="备注">
                                            <Input.TextArea />
                                        </Form.Item>
                                        <Form.Item label="数量">
                                            <Form.Item name={['DMRHead', 'quantity']}>
                                                <InputNumber min={0} />
                                            </Form.Item>
                                            <Input.Group compact>
                                                <Form.Item
                                                    name={['DMRHead', 'openDMR']}
                                                    valuePropName="checked">
                                                    <Checkbox disabled>未结</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>

                                    </Col>
                                </Row>

                            </TabPane>
                            <TabPane tab="明细" key="2">
                                <Table
                                    rowKey="id"
                                    size="small"
                                    columns={columns}
                                    loading={loading}
                                    dataSource={data.details}
                                    rowSelection={rowSelection}
                                    onRow={record => {
                                        return {
                                            onDoubleClick: event => { this.switchModal(true, record) },
                                        };
                                    }}
                                    footer={() =>
                                        <Space>
                                            <Button
                                                type="dashed"
                                                icon={<PlusOutlined />}
                                                onClick={() => this.switchModal(true)}>新建明细</Button>
                                            <Button
                                                type="dashed"
                                                danger
                                                icon={<CloseOutlined />}
                                                onClick={this.delDtl}
                                                disabled={selectedRowKeys.length <= 0}>删除选中</Button>
                                        </Space>
                                    }
                                />


                            </TabPane>
                        </Tabs>

                    </Card>
                </Form>
                <Card title="所有记录" extra={
                    <Space style={{ marginBottom: 16 }}>
                        <Button type="ghost"
                            onClick={() => this.fetchDatas()}
                            loading={loading2}
                            icon={<SyncOutlined />} ></Button>
                        <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                    </Space>
                }>
                    <Table
                        rowKey="id"
                        size="small"
                        columns={columns2}
                        loading={loading2}
                        dataSource={dataSource}
                        pagination={{
                            onChange: page => {
                                this.setState({ pageIndex: page }, () => {
                                    this.fetchDatas();
                                });
                            },
                            pageSize,
                            total: totalCount,
                        }}
                        onRow={record => {
                            return {
                                onDoubleClick: event => { this.getObj(record.dmrNum) },
                            };
                        }}
                    /></Card>
                <Modal
                    title="DMR明细"
                    visible={this.state.visible}
                    destroyOnClose={true}
                    onCancel={() => this.switchModal(false)}
                    footer={false}
                >
                    <DMRActn onRef={this.onRef} data={record} refreshData={this.getObj} />
                </Modal>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);